package com.dashu.device.netty.server;

import com.dashu.base.enums.device.ModuleType;
import com.dashu.device.netty.handler.CQServerHandler;
import com.dashu.device.netty.handler.HFServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;


import java.nio.charset.Charset;


/**
 * Created by lz on 2021/02/22
 */
@Slf4j
public class HFNettyServer {


    public static void init(int port , ModuleType moduleType){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ChannelFuture tcp_Future = socketRun(bossGroup, workerGroup , port , moduleType);
            if (tcp_Future == null)
                return;
            if (tcp_Future.isSuccess()) {
                System.out.println(moduleType + "HF协议启动成功:" + port);
            }
            // 等待关闭连接（阻塞式）
            tcp_Future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("CQNettyServer.init" , e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    private static ChannelFuture socketRun(EventLoopGroup bossGroup, EventLoopGroup workerGroup , int port , ModuleType moduleType) {
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast("logging",new LoggingHandler("DEBUG"));//设置log监听器，并且日志级别为debug，方便观察运行流程
                            ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
                            ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(1000000));//将多个消息转化成一个
                            ch.pipeline().addLast("http-encoder",new HttpResponseEncoder());
                            ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());//解决大码流的问题
                            ch.pipeline().addLast("http-server",new HFServerHandler());
                        }
                    });
            return b.bind(port).sync();
        } catch (Exception e) {
            log.error("CloudServer.socketRun" , e);
            return null;
        }
    }
}